import { dialog, ipcMain } from 'electron'
import simpleGit, { SimpleGit } from 'simple-git'
import { pathExists } from 'fs-extra'
import path from 'path'

//
let gitFolderPath = ''
let simpleGitInstance: SimpleGit
let gitSearchDaysCount = 7
let gitAllCommitsUsers: string[] = []
let gitChooseUsers: string[] = []

async function parseGitLog(logOutput: string) {
  const commits: GitLogItemInfo[] = []
  const lines = logOutput.split('\n')
  let currentCommit
  gitAllCommitsUsers = []

  for (const line of lines) {
    if (line.startsWith('commit')) {
      // 新的提交开始
      if (currentCommit) {
        commits.push(currentCommit)
      }
      currentCommit = { hash: line.split(' ')[1] }
    } else if (line.startsWith('Author:')) {
      const author = line.substring(8).trim()
      currentCommit.author = author
      if (!gitAllCommitsUsers.includes(author)) {
        gitAllCommitsUsers.push(author)
      }
    } else if (line.startsWith('Date:')) {
      currentCommit.date = line.substring(6).trim()
    } else if (line.startsWith('    ')) {
      // 提交消息
      currentCommit.message = line.trim()
    }
  }

  // 添加最后一个提交
  if (currentCommit) {
    commits.push(currentCommit)
  }

  return commits
}

async function getGitInfos(git: SimpleGit) {
  // git log three days
  const log = await git.raw('log', '--since', `${gitSearchDaysCount} days ago`)
  const currentLocalUser = await git.raw('config', 'user.name')
  const currentUserEmail = await git.raw('config', 'user.email')
  const currentUser = `${currentLocalUser.trim()} <${currentUserEmail.trim()}>`
  // 添加当前用户
  gitChooseUsers.push(currentUser)
  return {
    currentUser,
    log
  }
}

async function getParseGitLogInfos() {
  const gitInfo = await getGitInfos(simpleGitInstance)
  const parseLog = (await parseGitLog(gitInfo.log)).filter((item) => {
    // 过滤
    return gitChooseUsers.includes(item.author) && item.message.indexOf('See merge request') === -1
  })
  return {
    gitCurrentUser: gitInfo.currentUser,
    gitAllCommitsUsers: gitAllCommitsUsers,
    gitPath: gitFolderPath,
    gitInfo: parseLog
  }
}

export async function handleCustomApiMainChangeGitInfos(params: GitChangeParams) {
  if (gitFolderPath) {
    gitSearchDaysCount = params.day
    gitChooseUsers = JSON.parse(params.author)
    return getParseGitLogInfos()
  } else {
    return undefined
  }
}

export async function handleCustomApiMainOpenGitDirectoryDialog() {
  const folderPathInfo = await dialog.showOpenDialog({
    properties: ['openDirectory']
  })
  // 判断当前项目是否是一个git项目
  if (!folderPathInfo.canceled) {
    const filePath = folderPathInfo.filePaths[0]
    gitFolderPath = `${filePath}${path.sep}.git`
    // 判断当前项目是否是一个git项目
    if (await pathExists(gitFolderPath)) {
      // 如果有就获取相关的信息
      simpleGitInstance = simpleGit(filePath)
      // 返回git信息
      return await getParseGitLogInfos()
    } else {
      return undefined
    }
  } else {
    return {
      isCancel: true
    }
  }
}

export function setupModuleGit() {
  // 方法1
  ipcMain.handle('ipcPreloadMainOpenFolderGetPath', handleCustomApiMainOpenGitDirectoryDialog)

  // 方法2
  ipcMain.handle(
    'ipcPreloadMainChangeGitInfos',
    async (_, message) => await handleCustomApiMainChangeGitInfos(message)
  )
}
